package com.sphd.restaurantsystem.activitys;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.restaurantsystem.R;
import com.sphd.restaurantsystem.base.BaseActivity;
import com.sphd.restaurantsystem.base.RestaurantUrl;
import com.sphd.restaurantsystem.info.LoginInfo;
import com.sphd.restaurantsystem.presenter.ForgetPresenterImpl;
import com.sphd.restaurantsystem.utils.AppManager;
import com.sphd.restaurantsystem.utils.Constant;
import com.sphd.restaurantsystem.utils.TimeCount;
import com.sphd.restaurantsystem.view.ForgetView;
import com.wzh.frame.utils.JsonUtil;
import com.wzh.frame.utils.MD5keyBean;
import com.wzh.frame.utils.MyUtils;

import org.litepal.crud.DataSupport;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
    /*
    *
    * 修改密码界面
    * */
@RuntimePermissions
public class ForgetPasswordActivity extends BaseActivity implements TimeCount.TimeCountListener, Handler.Callback, ForgetView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.phone)
    MaterialEditText phone;
    @BindView(R.id.password_old)
    MaterialEditText passwordOld;
    @BindView(R.id.password)
    MaterialEditText password;
    @BindView(R.id.password_again)
    MaterialEditText passwordAgain;
    @BindView(R.id.register_getnum)
    Button registerGetnum;
    @BindView(R.id.yanzhangma)
    MaterialEditText yanzhangma;
    @BindView(R.id.yzm_relativelayout)
    RelativeLayout yzmRelativelayout;
    @BindView(R.id.update_btn)
    Button updateBtn;
    @BindView(R.id.content_forget_password)
    RelativeLayout contentForgetPassword;
    CountDownTimer countDownTimer;
    boolean ready = false;
    boolean isForget=false;
    private TimeCount time;//倒计时类的实现
    //此APPKEY仅供测试使用，且不定期失效，请到mob.com后台申请正式APPKEY
    private static String APPKEY = "1821134b197de";
    // 填写从短信SDK应用后台注册得到的APPSECRET
    private static String APPSECRET = "6f55db8a086cbad12b69def6c81d71f2";
    private boolean capacity = false;
    private ForgetPresenterImpl forgetPresenter;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password);
        ButterKnife.bind(this);
        addActivity(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(view -> finishActivity(this));
    }

    private void initView() {
        intent = getIntent();
        if (intent.getStringExtra(Constant.TAG).equals(LoginActivity.class.getSimpleName())) {
            setTitleBar(toolbar, "忘记密码");
            isForget=true;
        } else {
            setTitleBar(toolbar, "修改密码");
            yzmRelativelayout.setVisibility(View.GONE);
            isForget=false;
            phone.setText(DataSupport.findLast(LoginInfo.class).getStaff_phone());
            phone.setEnabled(false);
            phone.setShowClearButton(false);
            passwordOld.setVisibility(View.VISIBLE);
        }
        forgetPresenter = new ForgetPresenterImpl(this);
        initpermissions();
    }

    private void initpermissions() {
        ForgetPasswordActivityPermissionsDispatcher.onSuccedWithCheck(this);
    }

    @OnClick({R.id.register_getnum, R.id.update_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register_getnum:
                checkPhone();
                break;
            case R.id.update_btn:
                checkAll();
                break;
        }
    }

    private void checkPhone() {
        if (isEmpty(phone)) {
            phone.setError("手机号码不能为空");
        } else {
            if (MyUtils.isMobileNO(phone.getText().toString().trim())) {
                //// TODO: 2016/10/31 发送验证码
                SMSSDK.getVerificationCode("86", phone.getText().toString().trim());
                toast("已发送");
                time.start();//开始倒计时
            } else {
                phone.setError("请输入正确的手机号码");
            }
        }
    }

    private void checkAll() {
        if (isEmpty(phone)) {
            phone.setError("手机号码不能为空");
        } else {
            if (!MyUtils.isMobileNO(phone.getText().toString().trim())) {
                phone.setError("请输入正确的手机号码");
            } else {
                if (isEmpty(password)) {
                    password.setError("密码不能为空");
                } else {

                        if (isEmpty(passwordAgain)) {
                            passwordAgain.setError("确认密码不能为空");
                        } else {
                            if (!password.getText().toString().trim().equals(passwordAgain.getText().toString().trim())) {
                                passwordAgain.setError("两次密码不一致");
                            } else {
                                if (!isForget){
                                    if (isEmpty(passwordOld)){
                                        toast("请输入旧密码进行验证");
                                    }else {
                                        if (!MD5keyBean.MD5(passwordOld.getText().toString().trim()).equals(get(Constant.LOGINPWD,""))){
                                            toast("旧密码不对，请重新输入");
                                        }else {
                                            addData();
                                        }
                                    }
                                }else {
                                    if (capacity) {
                                        addData();
                                    } else {
                                        if (isEmpty(yanzhangma)) {
                                            yanzhangma.setError("验证码不能为空");
                                        } else {
                                            // TODO: 2016/10/31 验证验证码是否正确
                                            SMSSDK.submitVerificationCode("86", phone.getText().toString().trim(),
                                                    yanzhangma.getText().toString().trim());
                                        }
                                    }
                                }

                            }
                        }



                    }
                }
            }
        }
    private void addData() {
        forgetPresenter.addData(RestaurantUrl.Httptitle + RestaurantUrl.ChangePassword + "staffname=" + phone.getText().toString().trim() +
                "&staffpwd=" + MD5keyBean.MD5(password.getText().toString().trim()));
    }

    @Override
    public void sendRes(int res) {
        Log.e("RES===", res + "");
        if (res==1){
            toast("修改成功");
            DataSupport.deleteAll(LoginInfo.class);
            remove(Constant.LOGINPWD);
            remove(Constant.LOGINPHONE);
            remove(Constant.ISREMBER);


            AppManager.getAppManager().delAllActivityExceptMain(ForgetPasswordActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString(Constant.LOGINPHONE, phone.getText().toString().trim());
            bundle.putString(Constant.LOGINPWD, password.getText().toString().trim());
            intent.putExtras(bundle);
            startActivity(LoginActivity.class,intent);
            finish();



        }else {
            toast("修改失败");
        }

    }

    @NeedsPermission({Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onSucced() {
        initSdk();
    }

    private void initSdk() {
        if (!ready) {
            countDownTimer = new TimeCount(60000, 1000, this);//构造CountDownTimer对象
            // 初始化短信SDK
            SMSSDK.initSDK(this, APPKEY, APPSECRET, true);
            final Handler handler = new Handler(this);
            EventHandler eventHandler = new EventHandler() {
                public void afterEvent(int event, int result, Object data) {
                    Message msg = new Message();
                    msg.arg1 = event;
                    msg.arg2 = result;
                    msg.obj = data;
                    handler.sendMessage(msg);
                }
            };
            // 注册回调监听接口
            SMSSDK.registerEventHandler(eventHandler);
            ready = true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ForgetPasswordActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onCause(final PermissionRequest request) {
    }

    @OnPermissionDenied({Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onBreak() {
    }

    @OnNeverAskAgain({Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onNever() {
    }

    @Override
    public void onTicek(long ls) {
        registerGetnum.setClickable(false);
        registerGetnum.setText(ls / 1000 + "秒后获取");
    }

    @Override
    public void onFinish() {
        //计时完毕时触发
        registerGetnum.setText("重新验证");
//            tvObtain.setBackgroundResource(R.color.mycolor);
        registerGetnum.setClickable(true);
    }

    @Override
    public boolean handleMessage(Message msg) {
        int event = msg.arg1;
        int result = msg.arg2;
        Object data = msg.obj;
        if (result == SMSSDK.RESULT_COMPLETE) {
            if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                // TODO: 2016/10/31 验证通过 访问网络
                addData();
            } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                boolean smart = (Boolean) data;
                if (smart) {
                    //通过智能验证
                    toast("您已通过智能验证，无需再次输入验证码。");
                    yanzhangma.setVisibility(View.GONE);
                    capacity = true;
                } else {
                    //依然走短信验证
                    capacity = false;
                    yanzhangma.setVisibility(View.VISIBLE);
                }
            }
        } else if (result == SMSSDK.RESULT_ERROR) {
            ((Throwable) data).printStackTrace();
            Log.e("data", data.toString());
            toast(JsonUtil.getJsonObject(((Throwable) data).getMessage()).getString("detail"));
        }
        return false;
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
    }
}
